﻿using CRL.Core;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRL.RequestReport
{
    public class CountService
    {
        static ConcurrentDictionary<string, RequestCountBase> instances = new ConcurrentDictionary<string, RequestCountBase>();
        static CountService()
        {
            new ThreadWork().Start($"ReceiveTimeCount", () =>
            {
                foreach (var kv in instances)
                {
                    kv.Value.ClearTimeout();
                }
                return true;
            }, 60 * 60);
        }
        public static RequestCountBase GetInstance(string name)
        {
            var a = instances.TryGetValue(name, out var instance);
            if (!a)
            {
                instance = new RequestCountBase(name);
                var b = instances.TryAdd(name, instance);
            }
            return instance;
        }
        public static IDictionary<string, Dictionary<string, long>> ConvertDic(IDictionary<string, long> dic, char split)
        {
            var dic2 = new Dictionary<string, Dictionary<string, long>>(StringComparer.OrdinalIgnoreCase);
            if (!dic.Any())
            {
                return dic2;
            }
            var keys = dic.Keys.Select(b => b.Split(split)[0]).Distinct();
            foreach (var key in keys)
            {
                var values = dic.Where(b => b.Key.StartsWith(key));
                var dic3 = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
                foreach (var kv in values)
                {
                    var arry = kv.Key.Split(split);
                    var key2 = arry[0];
                    string name2 = "";
                    if (arry.Length > 1)
                    {
                        name2 = arry[1];
                    }
                    if (!dic3.ContainsKey(name2))
                    {
                        dic3.Add(name2, kv.Value);
                    }
                    else
                    {
                        dic3[name2] += kv.Value;
                    }
                }
                dic2.Add(key, dic3);
            }
            return dic2;
        }
        public static void Clear()
        {
            foreach(var kv in instances)
            {
                kv.Value.Clear();
            }

        }
    }
}
